function r2 = ecogRsquare(dat1,dat2,dim)
% r2 = ecogRsquare(dat1,dat2,dim) 
% determine rSquare-values from n-dim-mat dat1 and dat2 while summing through 
% n-th dimension

if nargin <3,
    if ndims(dat1)==2 && size(dat1,1)==1,
        dim=2;
    else
        dim=1;
    end
end

n1=size(dat1,dim);
n2=size(dat2,dim);

sum1=sum(dat1,dim);
sum2=sum(dat2,dim);
sumsqu1=sum(dat1.^2,dim);
sumsqu2=sum(dat2.^2,dim);

G=((sum1+sum2).^2)./(n1+n2);

r2=(sum1.^2./n1+sum2.^2./n2-G)./(sumsqu1+sumsqu2-G);